package com.project.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.isea.easyxls.ImpXls2ListObj;
import com.project.bean.AccountDocument;
import com.project.bean.MoneyRecord;
import com.project.bean.PersonnalDocument;
import com.project.bean.TransactionGather;
import com.project.dao.implement.AccountDocumentMapperExtImpl;
import com.project.dao.implement.MoneyRecordMapperExtImpl;
import com.project.dao.implement.PersonnalDocumentMapperExtImpl;
import com.project.dao.implement.TransactionGatherMapperExtImpl;
import com.project.utils.Constants;

public class FileUploadServlet extends HttpServlet {

	
	
/*	private final static String bufferPath = "C:/Temp/UploadRepository";  
    private final static String destPath = "C:/Temp/UploadStore"; */

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public FileUploadServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		/*response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();*/
		
		// TODO Auto-generated method stub  
		        boolean isMultipart = ServletFileUpload.isMultipartContent(req);  
		 
		        System.out.println("isMultipart = " + isMultipart);  
	  
		       // Create a factory for disk-based file items  
	        DiskFileItemFactory factory = new DiskFileItemFactory();  
		  
		       File repository = new File(Constants.bufferPath);  
		        factory.setRepository(repository); // Set the buffer directory.  
	        factory.setSizeThreshold(1024 * 100); // Set the size of buffer.  
	 
		       ServletFileUpload upload = new ServletFileUpload(factory);  
	           upload.setHeaderEncoding("UTF-8");
		       // Create a progress listener  
		       ProgressListener progressListener = new ProgressListener()  
	      {  
		           private long megaBytes = -1;  
		
		            /** 
	            * pBytesRead: The total number of bytes, which have been read so 
		            * far pContentLength: The total number of bytes, which are being 
		             * read. May be -1, if this number is unknown. pItems : The number 
	             * of the field, which is currently being read. (0 = no item so far, 
		             * 1 = first item is being read, ...) 
		             */  
	            public void update(long pBytesRead, long pContentLength, int pItems)  
		           {  
		                long mBytes = pBytesRead / 1000000;  
	              // "if" statement is for the purpose of reduce the progress  
		               // listeners activity  
		                 // For example, you might emit a message only, if the number of  
                // megabytes has changed:  
		               if (megaBytes == mBytes)  
		                 {  
		                     return;  
		                 }  
		                 megaBytes = mBytes;  
		                 System.out.println("We are currently reading item " + pItems);  
		                 if (pContentLength == -1)  
		                 {  
		                     System.out.println("So far, " + pBytesRead  
		                             + " bytes have been read.");  
		                 } else  
		                 {  
		                     System.out.println("So far, " + pBytesRead + " of "  
		                             + pContentLength + " bytes have been read.");  
		                 }  
		             }  
		         };  
		         //*******自己监听器
		         
		         myProgressListener myListener = new myProgressListener(req);
		         
		         //*********
		         upload.setProgressListener(myListener);  
		   
		         try  
		         {  
		             List<FileItem> items = upload.parseRequest(req);  
		   
		             Iterator<FileItem> iter = items.iterator();  
		   
		             while (iter.hasNext())  
		             {  
		                 FileItem item = iter.next();  
		   
		                 if (item.isFormField())  
		                 {  
		                     processFormField(item);  
		                 } else  
		                 {  
		                     processUploadedFile(item);  
		                     /*
		                      * 将上传的文件进行数据导入处理
		                      */
		                    /* String importFilePath = Constants.destPath+"/"+item.getName();
		                     DataImportMapperImpl dataImport = new  DataImportMapperImpl();
		            		 dataImport.dataImportMoneyRecord(importFilePath) ;
		            		 dataImport.dataImportAccountDocument(importFilePath);
		            		 dataImport.dataImportPersonalDocument(importFilePath);
		            		 dataImport.dataImportAccountTransactionGather(importFilePath);*/
		                     ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		            		 URL excelAccountUrl = classLoader.getResource(Constants.ExcelAccountDocumentMap);
		            		 URL excelTransUrl = classLoader.getResource(Constants.ExcelTransactiongatherMap);
		            		 URL excelMoneyUrl = classLoader.getResource(Constants.ExcelMoneyRecordMap);
		            		 URL excelPersonUrl = classLoader.getResource(Constants.ExcelPersonnalDocumentMap);
		            		 String importFilePath = Constants.destPath+"/"+item.getName();
		            		 File file = new File(importFilePath); 
		            		 List<TransactionGather> transactionGatherList;
		            		 List<AccountDocument> accountDocumentList;
		            		 List<MoneyRecord> moneyRecordList;
		            		 List<PersonnalDocument> personnalDocumentList;		 
		            		 transactionGatherList = (List<TransactionGather>) ImpXls2ListObj.impXls2ListObj(excelTransUrl.getFile(),file);
		            		 accountDocumentList = (List<AccountDocument>) ImpXls2ListObj.impXls2ListObj(excelAccountUrl.getFile(),file);
		            		 moneyRecordList = (List<MoneyRecord>) ImpXls2ListObj.impXls2ListObj(excelMoneyUrl.getFile(),file);
		            		 personnalDocumentList = (List<PersonnalDocument>) ImpXls2ListObj.impXls2ListObj(excelPersonUrl.getFile(),file);
		            		 AccountDocumentMapperExtImpl accountMapper = new AccountDocumentMapperExtImpl();
		            		 PersonnalDocumentMapperExtImpl personnalMapper = new PersonnalDocumentMapperExtImpl();
		            		 TransactionGatherMapperExtImpl transactionMapper = new TransactionGatherMapperExtImpl();
		            		 MoneyRecordMapperExtImpl moneyRecordMapper = new MoneyRecordMapperExtImpl();
		            		 accountMapper.insertBatch(accountDocumentList);
		            		 personnalMapper.insertBatch(personnalDocumentList);
		            		 transactionMapper.insertBatch(transactionGatherList);
		            		 moneyRecordMapper.insertBatch(moneyRecordList);
		            		 //  导入结束
		                 }  
		             }  
		         } catch (FileUploadException e)  
		        {  
            // TODO Auto-generated catch block  
		            e.printStackTrace();  
		       } catch (Exception e)  
		         {  
		             // TODO Auto-generated catch block  
		             e.printStackTrace();  
		         }  
		   
		         System.out.println("doPost");  
		     }  
		   
		    private void processFormField(FileItem item)  
		   {  
		        String name = item.getFieldName();  
	        String value = item.getString();  
		        System.out.println("name = " + name + ", value = " + value);  
		    }  
		  
		   private void processUploadedFile(FileItem item) throws Exception  
		    {  
		        String fieldName = item.getFieldName();  
		       String fileName = item.getName();  
		        String contentType = item.getContentType();  
		        boolean isInMemory = item.isInMemory();  
		       long sizeInBytes = item.getSize();  
		 
		       System.out.println("fieldName = " + fieldName + ", fileName = "  
		               + fileName + ", contentType = " + contentType  
		                + ", isInMemory = " + isInMemory + ", sizeInBytes = "  
		               + sizeInBytes);  
		        File fileToSave = new File(Constants.destPath, fileName);  
		  
		       item.write(fileToSave);  
		   }  

	

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
